<template>
    <van-nav-bar title="添加商品" left-arrow @click-left="handleLeft" v-if="!showSupplierName">
    </van-nav-bar>
    <div class="add_product" v-if="!showSupplierName">
        <div class="add_supplier-background">
            <van-form @submit="onSubmit" ref="formRef" validate-first scroll-to-error>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="supplierName" label="供应商名称"
                        v-model="homePageQueryParams.supplierName" is-link readonly placeholder="请选择" required
                        @click="showSupplierName = true" :rules="[
                            {
                                required: true,
                                trigger: 'onBlur',
                                message: '请选择供应商名称',
                            },
                        ]" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="styleName"
                        @input="(e) => { forbidRule(e, 'styleName', 'blank') }" label="商品名称"
                        v-model="homePageQueryParams.styleName" placeholder="请输入" required maxlength="50" :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入商品名称' }
                        ]" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="productCategoryName" label="商品类目" v-model="homePageQueryParams.productCategoryName"
                        is-link readonly input-align="right" error-message-align="right" placeholder="请选择"
                        @click="show = true" required :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择商品类目' },
                        ]" />
                    <div class="cascaderShade" v-if="cascaderShade"></div>
                    <van-popup v-model:show="show" round position="bottom">
                        <van-cascader v-model="cascaderValue" title="请选择商品类目" :options="options" @close="show = false"
                            @finish="onFinish" />
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="brandName" input-align="right" error-message-align="right" label="品牌"
                        v-model="homePageQueryParams.brandName" placeholder="请输入" maxlength="50" :rules="[
                            { required: false, trigger: 'onBlur', message: '请输入品牌名称' },
                            {
                                validator: validatorNumberBrand,
                                message: '请输入正确的品牌名称',
                            },
                        ]" />
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" name="styleCode" label="69码"
                    v-model:keyValue="homePageQueryParams.styleCode" placeholder="请输入" :rules="[
                        {
                            validator: validatorStyleCode,
                            message: '请输入正确内容',
                        },
                    ]">
                </formNumberKeyboard>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="tradeMode" label="贸易方式"
                        v-model="homePageQueryParams.tradeMode" required :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择贸易方式' },
                        ]">
                        <template #input>
                            <van-radio-group v-model="tradeModeChecked" direction="horizontal">
                                <van-radio v-for="item in tradeModeColumns" :key="item.value" :name="item.value">{{
                                    item.text }}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>
                <!-- <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="ingredient" label="材质" :rules="[
                        { required: false, trigger: 'onBlur', message: '请输入商品材质' },
                    ]" v-model="homePageQueryParams.ingredient" placeholder="请输入" maxlength="50"
                        @input="(e) => { forbidRule(e, 'ingredient', 'emoji') }" />
                </van-cell-group> -->
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="specs" label="规格/材质" :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入规格/材质名称' },
                    ]" v-model="homePageQueryParams.specs" placeholder="请输入" required maxlength="200"
                        @input="(e) => { forbidRule(e, 'specs', 'emoji') }" />
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" name="tax" label="平台扣点"
                    v-model:keyValue="homePageQueryParams.tax" placeholder="请输入" required :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入平台扣点' },
                        {
                            validator: validatorcommission,
                            message: '请输入正确内容：整数或者保留两位小数',
                        },
                    ]" extraKey=".">
                    <div style="display: flex;align-items: center;">
                        <span style="margin-right: 5px;">%</span>
                        <PointButton @onClick="isPoint = true" />
                    </div>
                </formNumberKeyboard>
                <div>
                    <div class="mechanism_title">机制一</div>
                    <van-cell-group inset>
                        <van-field input-align="right" error-message-align="right" name="cooperationMode" label="合作方式"
                            v-model="homePageQueryParams.cooperationMode" readonly placeholder="请选择" required :rules="[
                                { required: true, trigger: 'onBlur', message: '请选择合作方式' },
                            ]">
                            <template #input>
                                <van-radio-group v-model="homePageQueryParams.cooperationMode" direction="horizontal">
                                    <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                        :name="item.value">{{
                                            item.text }}</van-radio>
                                </van-radio-group>
                            </template>
                        </van-field>
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field input-align="right" error-message-align="right" name="liveStreamingMechanism"
                            label="机制" maxlength="12" v-model="homePageQueryParams.liveStreamingMechanism"
                            @input="(e) => { forbidRule(e, 'liveStreamingMechanism', 'blank') }" placeholder="请输入"
                            required :rules="[
                                { required: true, trigger: 'onBlur', message: '请输入机制' },
                            ]" />
                    </van-cell-group>
                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode == '分佣'"
                        name="price" label="售价" v-model:keyValue="homePageQueryParams.price" placeholder="请输入" required
                        :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入售价' },
                            {
                                validator: validatorNumber,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey="." />

                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode == '分佣'"
                        name="commission" label="佣金" v-model:keyValue="homePageQueryParams.commission" placeholder="请输入"
                        required :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入佣金' },
                            {
                                validator: validatorcommission,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey=".">
                        %
                    </formNumberKeyboard>
                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode == '分佣'"
                        name="brokerage" label="补充佣金" v-model:keyValue="homePageQueryParams.brokerage" placeholder="请输入"
                        :rules="[
                            {
                                validator: validatorbrokerage,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey=".">
                        %
                    </formNumberKeyboard>

                    <van-cell-group inset v-if="homePageQueryParams.cooperationMode == '分佣'">
                        <van-field input-align="right" error-message-align="right" name="costPrice" label="成本"
                            v-model="homePageQueryParams.costPrice" readonly required placeholder="请输入" />
                    </van-cell-group>
                    <formNumberKeyboard v-else :formRef="formRef" name="costPrice" label="成本"
                        v-model:keyValue="homePageQueryParams.costPrice" placeholder="请输入"
                        :required="homePageQueryParams.cooperationMode == '供货'" :rules="[
                            {
                                validator: validatorNumbercostPrice,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey="." />
                    <div class="add_mechanism" @click="addMechanism(2)" v-if="mechanismArr.length == 1">
                        <van-image :src="tianjia"></van-image>
                        <div class="title">添加机制</div>
                    </div>
                </div>
                <div v-if="mechanismArr.indexOf(2) !== -1">
                    <div class="mechanism_title">
                        机制二
                        <div class="delete_mechanism" @click="deleteMechanism(2)">
                            <van-image :src="shanchu"></van-image>
                            <div class="title">删除机制</div>
                        </div>
                    </div>
                    <van-cell-group inset>
                        <van-field input-align="right" error-message-align="right" name="cooperationMode2" label="合作方式"
                            readonly placeholder="请选择" clearable :rules="[
                                { required: false, trigger: 'onBlur', message: '请选择合作方式' },
                            ]">

                            <template #input>
                                <van-radio-group v-model="homePageQueryParams.cooperationMode2" direction="horizontal">
                                    <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                        :name="item.value">{{
                                            item.text }}</van-radio>
                                </van-radio-group>
                            </template>
                        </van-field>
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field input-align="right" error-message-align="right" name="liveStreamingMechanism2"
                            label="机制" maxlength="12" v-model="homePageQueryParams.liveStreamingMechanism2"
                            :required="!!homePageQueryParams.cooperationMode2"
                            @input="(e) => { forbidRule(e, 'liveStreamingMechanism2', 'blank') }" placeholder="请输入"
                            :rules="[
                                { validator: validators2, message: '请输入机制' },
                            ]" />
                    </van-cell-group>
                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode2 == '分佣'"
                        name="price2" label="售价" v-model:keyValue="homePageQueryParams.price2" placeholder="请输入"
                        :required="homePageQueryParams.cooperationMode2 == '分佣'" :rules="[
                            { validator: validators2, message: '请输入售价' },
                            {
                                validator: validatorNumber2,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey="." />

                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode2 == '分佣'"
                        name="commission2" label="佣金" v-model:keyValue="homePageQueryParams.commission2"
                        placeholder="请输入" :required="homePageQueryParams.cooperationMode2 == '分佣'" :rules="[
                            { validator: validators2, message: '请输入佣金' },
                            {
                                validator: validatorcommission2,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey=".">
                        %
                    </formNumberKeyboard>
                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode2 == '分佣'"
                        name="brokerage2" label="补充佣金" v-model:keyValue="homePageQueryParams.brokerage2"
                        placeholder="请输入" :rules="[
                            {
                                validator: validatorbrokerage2,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey=".">
                        %
                    </formNumberKeyboard>

                    <van-cell-group inset v-if="homePageQueryParams.cooperationMode2 == '分佣'">
                        <van-field input-align="right" error-message-align="right" name="costPrice2" label="成本"
                            v-model="homePageQueryParams.costPrice2" readonly required placeholder="请输入" />
                    </van-cell-group>
                    <formNumberKeyboard v-else :formRef="formRef" name="costPrice2" label="成本"
                        v-model:keyValue="homePageQueryParams.costPrice2" placeholder="请输入"
                        :required="homePageQueryParams.cooperationMode2 == '供货'" :rules="[
                            {
                                validator: validatorNumbercostPrice2,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey="." />
                    <div class="add_mechanism" @click="addMechanism(3)" v-if="mechanismArr.length == 2">
                        <van-image :src="tianjia"></van-image>
                        <div class="title">添加机制</div>
                    </div>
                </div>
                <div v-if="mechanismArr.indexOf(3) !== -1">
                    <div class="mechanism_title">
                        机制三
                        <div class="delete_mechanism" @click="deleteMechanism(3)">
                            <van-image :src="shanchu"></van-image>
                            <div class="title">删除机制</div>
                        </div>
                    </div>
                    <van-cell-group inset>
                        <van-field input-align="right" error-message-align="right" name="cooperationMode3" label="合作方式"
                            v-model="homePageQueryParams.cooperationMode3" readonly placeholder="请选择" :rules="[
                                { required: false, trigger: 'onBlur', message: '请选择合作方式' },
                            ]">
                            <template #input>
                                <van-radio-group v-model="homePageQueryParams.cooperationMode3" direction="horizontal">
                                    <van-radio v-for="item in cooperationModeColumns" :key="item.value"
                                        :name="item.value">{{
                                            item.text }}</van-radio>
                                </van-radio-group>
                            </template>
                        </van-field>
                    </van-cell-group>
                    <van-cell-group inset>
                        <van-field input-align="right" error-message-align="right" name="liveStreamingMechanism3"
                            label="机制" maxlength="12" v-model="homePageQueryParams.liveStreamingMechanism3"
                            @input="(e) => { forbidRule(e, 'liveStreamingMechanism3', 'blank') }" placeholder="请输入"
                            :required="!!homePageQueryParams.cooperationMode3" :rules="[
                                { validator: validators3, message: '请输入机制' },
                            ]" />
                    </van-cell-group>
                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode3 == '分佣'"
                        name="price3" label="售价" :required="homePageQueryParams.cooperationMode3 == '分佣'"
                        v-model:keyValue="homePageQueryParams.price3" placeholder="请输入" :rules="[
                            { validator: validators3, message: '请输入售价' },
                            {
                                validator: validatorNumber2,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey="." />

                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode3 == '分佣'"
                        name="commission3" label="佣金" :required="homePageQueryParams.cooperationMode3 == '分佣'"
                        v-model:keyValue="homePageQueryParams.commission3" placeholder="请输入" :rules="[
                            { validator: validators3, message: '请输入佣金' },
                            {
                                validator: validatorcommission2,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey=".">
                        %
                    </formNumberKeyboard>
                    <formNumberKeyboard :formRef="formRef" v-if="homePageQueryParams.cooperationMode3 == '分佣'"
                        name="brokerage3" label="补充佣金" v-model:keyValue="homePageQueryParams.brokerage3"
                        placeholder="请输入" :rules="[
                            {
                                validator: validatorbrokerage3,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey=".">
                        %
                    </formNumberKeyboard>

                    <van-cell-group inset v-if="homePageQueryParams.cooperationMode3 == '分佣'">
                        <van-field input-align="right" error-message-align="right" name="costPrice3" label="成本"
                            v-model="homePageQueryParams.costPrice3" readonly required placeholder="请输入" />
                    </van-cell-group>
                    <formNumberKeyboard v-else :formRef="formRef" name="costPrice3" label="成本"
                        v-model:keyValue="homePageQueryParams.costPrice3" placeholder="请输入"
                        :required="homePageQueryParams.cooperationMode3 == '供货'" :rules="[
                            {
                                validator: validatorNumbercostPrice3,
                                message: '请输入正确内容：整数或者保留两位小数',
                            },
                        ]" extraKey="." />
                </div>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="discountPrice" label="能否破价"
                        v-model="homePageQueryParams.discountPrice" required :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择能否破价' },
                        ]">
                        <template #input>
                            <van-radio-group v-model="discountPriceChecked" direction="horizontal">
                                <van-radio v-for="item in discountPriceColumns" :key="item.value" :name="item.value">{{
                                    item.text }}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset v-if="hm_warehouse_show">
                    <van-field input-align="right" error-message-align="right" name="warehouse" label="走仓" required
                        :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择是否走仓' },
                        ]" v-model="homePageQueryParams.warehouse">
                        <template #input>
                            <van-radio-group v-model="warehouseChecked" direction="horizontal">
                                <van-radio v-for="item in discountWarehouse" :key="item.value" :name="item.value">{{
                                    item.text }}</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" name="historyPrice" label="历史最低售价"
                    v-model:keyValue="homePageQueryParams.historyPrice" placeholder="请输入" :rules="[
                        {
                            required: false,
                            trigger: 'onBlur',
                            message: '请输入历史最低售价',
                        },
                        {
                            validator: validatorPrice,
                            message: '请输入正确的历史最低售价',
                        },
                    ]" extraKey="." />
                <van-cell-group inset>
                    <van-field v-model="homePageQueryParams.sellingPoints" input-align="right"
                        error-message-align="right" maxlength="189" rows="1" autosize label="卖点" name="sellingPoints"
                        @input="(e) => { forbidRule(e, 'sellingPoints', 'emoji') }" placeholder="请输入卖点" required :rules="[
                            { validator: validSpace, message: '请输入卖点' }
                        ]" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field v-model="homePageQueryParams.groupName" input-align="right" error-message-align="right"
                        maxlength="20" autosize label="对接群名" @input="(e) => { forbidRule(e, 'groupName', 'emoji') }"
                        placeholder="请输入对接群名" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="deliveryTime" label="发货时间"
                        v-model="homePageQueryParams.deliveryTime" placeholder="请输入发货时间" maxlength="48"
                        @input="(e) => { forbidRule(e, 'deliveryTime', 'emoji') }" required :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入发货时间' }
                        ]" />
                </van-cell-group>
                <van-cell-group inset>
                    <!-- <van-field v-model="homePageQueryParams.placeDelivery" is-link readonly input-align="right"
                        error-message-align="right" name="placeDelivery" label="发货地" placeholder="点击选择省市区"
                        @click="showBusinessAddress = true" />
                    <van-popup v-model:show="showBusinessAddress" position="bottom">
                        <van-area title="发货地" :area-list="areaList" @confirm="onConfirmBusinessAddress"
                            @cancel="showBusinessAddress = false" v-model="homePageQueryParams.placeDeliveryId" />
                    </van-popup> -->
                    <van-field v-model="homePageQueryParams.placeDelivery" input-align="right"
                        error-message-align="right" maxlength="100" rows="1" autosize label="发货地"
                        @input="(e) => { forbidRule(e, 'placeDelivery', 'emoji') }" placeholder="请输入发货地" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="logistics" label="物流/快递" :rules="[
                        { required: false, trigger: 'onBlur', message: '请输入商品物流/快递' },
                    ]" v-model="homePageQueryParams.logistics" placeholder="请输入" maxlength="20"
                        @input="(e) => { forbidRule(e, 'logistics', 'emoji') }" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="eligibility" label="适用人群"
                        v-model="homePageQueryParams.eligibility" placeholder="请输入" maxlength="20"
                        @input="(e) => { forbidRule(e, 'eligibility', 'emoji') }" />
                </van-cell-group>
                <formNumberKeyboard :formRef="formRef" name="factoryStockNum" label="厂家可用库存"
                    v-model:keyValue="homePageQueryParams.factoryStockNum" placeholder="请输入" maxlength="8" required
                    :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入厂家可用库存' }
                    ]" />
                <van-cell-group inset>
                    <van-field v-model="homePageQueryParams.noSendArea" input-align="right" error-message-align="right"
                        maxlength="72" rows="1" autosize label="不发货地区"
                        @input="(e) => { forbidRule(e, 'noSendArea', 'emoji') }" placeholder="请输入不发货地区" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="bigDate" label="大货时间" v-model="homePageQueryParams.bigDate" is-link
                        input-align="right" error-message-align="right" readonly placeholder="请选择" required :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择大货时间' }
                        ]" @click="showDeliveryTime = true" />
                    <van-popup v-model:show="showDeliveryTime" position="bottom">
                        <van-date-picker @confirm="onConfirmBottom" @cancel="showDeliveryTime = false"
                            v-model="currentDateBottom" :min-date="minDate" />
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="isPackageRemind" label="包销提醒" input-align="right" error-message-align="right">
                        <template #input>
                            <van-switch v-model="homePageQueryParams.isPackageRemind" />
                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="packageDeadline" label="包销时限" v-model="homePageQueryParams.packageDeadline" is-link
                        input-align="right" error-message-align="right" readonly placeholder="请选择"
                        @click="showUnderwritingTimes = true" />
                    <van-popup v-model:show="showUnderwritingTimes" position="bottom">
                        <van-picker title="选择包销时限" :columns="underwritingTimesColumns"
                            @confirm="onConfirmUnderwritingTimes" @cancel="showUnderwritingTimes = false" />
                    </van-popup>
                </van-cell-group>

                <div class="image-title">
                    <div class="require_icon">*</div>
                    无AB货截图
                </div>
                <van-cell-group inset>
                    <van-field name="noAbImage" label="" v-model="homePageQueryParams.noAbImage" :rules="[
                        { required: true, trigger: 'onBlur', message: '请上传无AB货截图' }
                    ]">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="abImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image v-if="element.url"
                                                :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)"></van-image>
                                            <van-icon name="cross" v-if="element.url" color="#fff" @click.prevent="
                                                deleteImg(
                                                    abImageList,
                                                    index,
                                                )
                                                " />
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="abImageList.length < 1"
                                    @click="postImage('noAbImage', 1)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title">
                    大货视频
                </div>
                <van-cell-group inset>
                    <van-field name="大货视频" label="" v-model="homePageQueryParams.bigVideo">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="productVideoList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <VideoDisplay :src="element.url" v-if="element.url" />
                                            <van-icon name="cross" class="delete_icon" v-if="element.url" color="#fff"
                                                @click.prevent="
                                                    deleteImg(
                                                        productVideoList,
                                                        index,
                                                    )
                                                    " />
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="productVideoList.length < 1"
                                    @click="postVideo('bigVideo', 1)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title">
                    商品图
                </div>
                <van-cell-group inset>
                    <van-field name="商品图" label="" v-model="homePageQueryParams.productImage">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="productImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <!-- <div v-for="(item, index) in productImageList" :key="index" class="imgList"> -->
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)" v-if="element.url"></van-image>
                                            <van-icon name="cross" color="#fff" v-if="element.url" @click.prevent="
                                                deleteImg(
                                                    productImageList,
                                                    index,
                                                )
                                                " />
                                            <!-- </div> -->
                                        </div>
                                    </template>
                                </draggable>

                                <van-image :src="upload" v-if="productImageList.length < 5"
                                    @click="postImage('productImage', 5)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title">
                    备案凭证/行政许可批件
                </div>
                <van-cell-group inset>
                    <van-field name="备案凭证/行政许可批件" label="" v-model="homePageQueryParams.voucherImage">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="voucherImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <!-- <div v-for="(item, index) in productImageList" :key="index" class="imgList"> -->
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                v-if="element.url" @click="enlargeImage(element.url)"></van-image>
                                            <van-icon name="cross" v-if="element.url" color="#fff" @click.prevent="
                                                deleteImg(
                                                    voucherImageList,
                                                    index,
                                                )
                                                " />
                                            <!-- </div> -->
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="voucherImageList.length < 5"
                                    @click="postImage('voucherImage', 5)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title">
                    其他资质
                </div>
                <van-cell-group inset>
                    <van-field name="其他资质" label="" v-model="homePageQueryParams.otherImage">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="otherImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <!-- <div v-for="(item, index) in productImageList" :key="index" class="imgList"> -->
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image v-if="element.url"
                                                :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)"></van-image>
                                            <van-icon name="cross" v-if="element.url" color="#fff" @click.prevent="
                                                deleteImg(
                                                    otherImageList,
                                                    index,
                                                )
                                                " />
                                            <!-- </div> -->
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="otherImageList.length < 10"
                                    @click="postImage('otherImage', 10)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title" v-if="tradeModeChecked == '进口'">
                    进口货物/原材料报关单
                </div>
                <van-cell-group inset>
                    <van-field name="进口货物/原材料报关单" label="" v-model="homePageQueryParams.customsDeclarationImage"
                        v-if="tradeModeChecked == '进口'">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="customsDeclarationImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image v-if="element.url"
                                                :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)"></van-image>
                                            <van-icon v-if="element.url" name="cross" color="#fff" @click.prevent="
                                                deleteImg(
                                                    customsDeclarationImageList,
                                                    index,
                                                )
                                                " />
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="customsDeclarationImageList.length < 5"
                                    @click="postImage('customsDeclarationImage', 5)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title" v-if="tradeModeChecked == '进口'">
                    进口产品备案材料
                </div>
                <van-cell-group inset>
                    <van-field name="进口产品备案材料" label="" v-model="homePageQueryParams.customsInformationImage"
                        v-if="tradeModeChecked == '进口'">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="customsInformationImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image v-if="element.url"
                                                :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)"></van-image>
                                            <van-icon name="cross" v-if="element.url" color="#fff" @click.prevent="
                                                deleteImg(
                                                    customsInformationImageList,
                                                    index,
                                                )
                                                " />
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="customsInformationImageList.length < 5"
                                    @click="postImage('customsInformationImage', 5)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title" v-if="tradeModeChecked == '进口'">
                    进口产品原材料检验检疫证明
                </div>
                <van-cell-group inset>
                    <van-field name="进口产品原材料检验检疫证明" label="" v-model="homePageQueryParams.customsInspectionImage"
                        v-if="tradeModeChecked == '进口'">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="customsInspectionImageList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image v-if="element.url"
                                                :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)"></van-image>
                                            <van-icon name="cross" v-if="element.url" color="#fff" @click.prevent="
                                                deleteImg(
                                                    customsInspectionImageList,
                                                    index,
                                                )
                                                " />
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="customsInspectionImageList.length < 5"
                                    @click="postImage('customsInspectionImage', 5)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div class="image-title" v-if="tradeModeChecked == '进口'">
                    检测报告
                </div>
                <van-cell-group inset>
                    <van-field name="检测报告" label="" v-if="tradeModeChecked == '进口'"
                        v-model="homePageQueryParams.customsTestReportImgae">
                        <template #input>
                            <div class="value">
                                <draggable class='dragge_box' :list="customsTestReportImgaeList" ghost-class="ghost"
                                    chosen-class="chosenClass" animation="300" :delay="300" @start="onStart"
                                    @end="onEnd">
                                    <template #item="{ element, index }">
                                        <div class="imgList">
                                            <div class="loading_pic" v-if="!element.url">
                                                <van-loading type="spinner" size="20" />
                                            </div>
                                            <van-image v-if="element.url"
                                                :src="element.url + '?x-oss-process=image/resize,w_300'"
                                                @click="enlargeImage(element.url)"></van-image>
                                            <van-icon name="cross" v-if="element.url" color="#fff" @click.prevent="
                                                deleteImg(
                                                    customsTestReportImgaeList,
                                                    index,
                                                )
                                                " />
                                        </div>
                                    </template>
                                </draggable>
                                <van-image :src="upload" v-if="customsTestReportImgaeList.length < 5"
                                    @click="postImage('customsTestReportImgae', 5)" v-throttle:click></van-image>
                            </div>
                        </template>
                    </van-field>
                </van-cell-group>
                <div style="width: 100%; bottom: 0; margin-top: 30px">
                    <van-button round block :loading="loading" loading-text="执行中..." type="primary" native-type="submit"
                        v-throttle:click>
                        保存
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
    <SupplierScreen :isShow="showSupplierName" @cancel="showSupplierName = false" @submit="onConfirmSupplierName">
    </SupplierScreen>
    <Point :show="isPoint" v-model:costPrice="homePageQueryParams.costPrice"
        v-model:costPrice2="homePageQueryParams.costPrice2" v-model:costPrice3="homePageQueryParams.costPrice3"
        :mechanismArr="mechanismArr" :data="homePageQueryParams" @clone="isPoint = false" />
</template>
<script setup lang="ts">
import VideoDisplay from '@/components/videoDisplay/index.vue'
import {
    getDicts,
    addProduct,
    getCategoryList,
} from "@/api/productList/index";
import { showSuccessToast } from "vant";
import { onUnmounted, ref, watchEffect, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { showImagePreview, showFailToast } from "vant";
import { getEnvValue } from "@/utils/index";
import SupplierScreen from '@/components/SupplierScreen/index.vue'
import formNumberKeyboard from "@/components/formNumberKeyboard/index.vue";
import Point from '@/views/addProduct/components/point.vue'
import PointButton from '@/views/addProduct/components/pointButton.vue'
import { handleImageUpdate } from '@/utils/handleImageUpdate';
import draggable from 'vuedraggable';
const upload = new URL("@/assets/home/upload.png", import.meta.url).href;
const tianjia = new URL("@/assets/productHome/icon_tianjia1.png", import.meta.url).href;
const shanchu = new URL("@/assets/productHome/icon_shanchu.png", import.meta.url).href;
//拖拽开始的事件
const onStart = () => {
}
//拖拽结束的事件
const onEnd = () => {
}
const store = loginStore();
const formRef = ref()
const { token } = storeToRefs(store);
const router = useRouter();
const route = useRoute();
const tradeModeChecked = ref();
const homePageQueryParams = ref({
    supplierName: "",
    styleName: "",
    category: "",
    styleCode: "",
    sellingPoints: "",
    tradeMode: "",
    cooperationMode: "",
    price: "",
    costPrice: "",
    liveStreamingMechanism: "",
    commission: "",
    brokerage: "",
    productCategoryName: "",
    categoryId: "",
    brandName: "",

    cooperationMode2: "",
    price2: "",
    costPrice2: "",
    liveStreamingMechanism2: "",
    commission2: "",
    brokerage2: "",

    cooperationMode3: "",
    price3: "",
    costPrice3: "",
    liveStreamingMechanism3: "",
    commission3: "",
    brokerage3: "",

    discountPrice: "",
    supplierId: "",
    productImage: "",
    voucherImage: "",
    otherImage: "",
    customsDeclarationImage: "",
    customsInformationImage: "",
    customsInspectionImage: "",
    customsTestReportImgae: "",
    specs: "",
    // ingredient: "",
    warehouse: "",
    groupName: "",
    deliveryTime: "",
    placeDelivery: "",
    logistics: "",
    eligibility: "",
    factoryStockNum: "",
    noSendArea: "",
    placeDeliveryId: "",
    tax: '',
    historyPrice: "",

    bigDate: "",
    isPackageRemind: "",
    packageDeadline: "",
    noAbImage: "",
    bigVideo: "",
});
const isPoint = ref(false)      // 扣点弹框开关
const productImageList = ref<any[]>([]);
const abImageList = ref<any[]>([]);
const productVideoList = ref<any[]>([]);
const voucherImageList = ref<any[]>([]);
const otherImageList = ref<any[]>([]);
const customsDeclarationImageList = ref<any[]>([]);
const customsInformationImageList = ref<any[]>([]);
const customsInspectionImageList = ref<any[]>([]);
const customsTestReportImgaeList = ref<any[]>([]);

const showSupplierName = ref(false);

const show = ref(false);
const cascaderValue = ref('');
const options = ref();
const tradeModeColumns = ref<any>([]);
const cooperationModeColumns = ref<any>([]);
const discountPriceColumns = ref<any>([]);
const discountPriceChecked = ref()

const loading = ref(false)

const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const date = today.getDate();
// 当前时间
const currentTime = ref([
    year + "",
    month < 10 ? "0" + month : month + "",
    date < 10 ? "0" + date : date + "",
]);
const currentDateBottom = ref([
    year + "",
    month < 10 ? "0" + month : month + "",
    date < 10 ? "0" + date : date + "",
]);
const showDeliveryTime = ref(false)

const underwritingTimesColumns = ref([
    { text: '3个月', value: '3' },
    { text: '6个月', value: '6' },
    { text: '12个月', value: '12' },
    { text: '永久', value: '0' },
])
const showUnderwritingTimes = ref(false)

/** 上级路由 */
const fromRoute = computed(() => {
    return route.query.from;
});


watchEffect(() => {
    // 监听平台扣点，售价，佣金，补充佣金，动态计算成本
    if (homePageQueryParams.value.cooperationMode === '分佣' && homePageQueryParams.value.price) {
        let costPrice = Number(homePageQueryParams.value.price || 0) * (1 - ((Number(homePageQueryParams.value.commission || 0) / 100) + (Number(homePageQueryParams.value.brokerage || 0) / 100) + (Number(homePageQueryParams.value.tax || 0) / 100)))
        homePageQueryParams.value.costPrice = costPrice.toFixed(2)
    }
    if (homePageQueryParams.value.cooperationMode2 === '分佣' && homePageQueryParams.value.price2) {
        let costPrice2 = Number(homePageQueryParams.value.price2 || 0) * (1 - ((Number(homePageQueryParams.value.commission2 || 0) / 100) + (Number(homePageQueryParams.value.brokerage2 || 0) / 100) + (Number(homePageQueryParams.value.tax || 0) / 100)))
        homePageQueryParams.value.costPrice2 = costPrice2.toFixed(2)
    }
    if (homePageQueryParams.value.cooperationMode3 === '分佣' && homePageQueryParams.value.price3) {
        let costPrice3 = Number(homePageQueryParams.value.price3 || 0) * (1 - ((Number(homePageQueryParams.value.commission3 || 0) / 100) + (Number(homePageQueryParams.value.brokerage3 || 0) / 100) + (Number(homePageQueryParams.value.tax || 0) / 100)))
        homePageQueryParams.value.costPrice3 = costPrice3.toFixed(2)
    }
})
/** 日期选择 */
const onConfirmBottom = () => {
    showDeliveryTime.value = false
    homePageQueryParams.value.bigDate = currentDateBottom.value.join("-")
}
// 限制最小可选时间
const minDate = computed(() => {
    return new Date(currentTime.value.join('/'))
})

// 集合
const mechanismArr = ref([1])

// 限制必填情况下空格
const validSpace = (val) => {
    if (val) {
        return !/^[\s]*$/.test(val)
    } else {
        return false
    }
}

// 历史最低售价
const validatorPrice = (val) => {
    if (val) {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val)
    } else {
        return true
    }
}

const validatorStyleCode = (val) => {
    if (val) {
        return /^[0-9]{3,13}$/.test(val)
    } else {
        return true
    }
}
const validatorNumber = (val) => {
    return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
}

const validatorNumbercostPrice = (val: any) => {
    if (homePageQueryParams.value.cooperationMode == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (homePageQueryParams.value.cooperationMode == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}

// 机制二机制三  分佣时非必填 为空时非必填 供货时必填
const validatorNumbercostPrice2 = (val) => {
    if (homePageQueryParams.value.cooperationMode2 == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (homePageQueryParams.value.cooperationMode2 == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}
const validatorNumbercostPrice3 = (val) => {
    if (homePageQueryParams.value.cooperationMode3 == '分佣') {
        if (val) {
            return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
        } else {
            return true
        }
    } else if (homePageQueryParams.value.cooperationMode3 == '') {
        return true
    } else {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    }
}
const validators2 = (value) => {
    if (homePageQueryParams.value.cooperationMode2) {
        if (value) {
            return true
        } else {
            return false
        }
    } else {
        return true
    }
}
const validators3 = (value) => {
    if (homePageQueryParams.value.cooperationMode3) {
        if (value) {
            return true
        } else {
            return false
        }
    } else {
        return true
    }
}
const validatorNumber2 = (val) => {
    if (val) {
        return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val);
    } else {
        return true
    }
}

const validatorcommission2 = (val) => {
    if (val) {
        return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
    } else {
        return true
    }
}

const validatorcommission = (val) => /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
const validatorbrokerage = (val) => {
    if (homePageQueryParams.value.cooperationMode == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorbrokerage2 = (val) => {
    if (homePageQueryParams.value.cooperationMode2 == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorbrokerage3 = (val) => {
    if (homePageQueryParams.value.cooperationMode3 == '分佣') {
        if (val) {
            return /^(([1-9]?\d(\.\d{1,2})?)|100|100.00)$/.test(val);
        } else {
            return true
        }
    } else {
        return false
    }
}
const validatorNumberBrand = (val) => {
    if (val) {
        return /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);
    } else {
        return true
    }
}
// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        homePageQueryParams.value[key] = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        homePageQueryParams.value[key] = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    }
}

/** 添加机制 */
const addMechanism = (index: number) => {
    mechanismArr.value.push(index)
}
/** 删除机制 */
const deleteMechanism = (index: number) => {
    // 当机制二删除并且机制三也存在得情况 删除机制三 保留机制二
    if (index == 2 && mechanismArr.value.length == 3) {
        mechanismArr.value.splice(2, 1)
        homePageQueryParams.value.cooperationMode2 = homePageQueryParams.value.cooperationMode3
        homePageQueryParams.value.price2 = homePageQueryParams.value.price3
        homePageQueryParams.value.costPrice2 = homePageQueryParams.value.costPrice3
        homePageQueryParams.value.liveStreamingMechanism2 = homePageQueryParams.value.liveStreamingMechanism3
        homePageQueryParams.value.commission2 = homePageQueryParams.value.commission3
        homePageQueryParams.value.brokerage2 = homePageQueryParams.value.brokerage3

        homePageQueryParams.value.cooperationMode3 = ""
        homePageQueryParams.value.price3 = ""
        homePageQueryParams.value.costPrice3 = ""
        homePageQueryParams.value.liveStreamingMechanism3 = ""
        homePageQueryParams.value.commission3 = ""
        homePageQueryParams.value.brokerage3 = ""
    } else {
        let indexs = mechanismArr.value.indexOf(index)
        mechanismArr.value.splice(indexs, 1)
        if (index == 2) {
            homePageQueryParams.value.cooperationMode2 = ""
            homePageQueryParams.value.price2 = ""
            homePageQueryParams.value.costPrice2 = ""
            homePageQueryParams.value.liveStreamingMechanism2 = ""
            homePageQueryParams.value.commission2 = ""
            homePageQueryParams.value.brokerage2 = ""
        } else if (index == 3) {
            homePageQueryParams.value.cooperationMode3 = ""
            homePageQueryParams.value.price3 = ""
            homePageQueryParams.value.costPrice3 = ""
            homePageQueryParams.value.liveStreamingMechanism3 = ""
            homePageQueryParams.value.commission3 = ""
            homePageQueryParams.value.brokerage3 = ""
        }
    }
}
/** 包销时限关闭 */
const onConfirmUnderwritingTimes = ({ selectedOptions }) => {
    homePageQueryParams.value.packageDeadline = selectedOptions[0]?.text;
    showUnderwritingTimes.value = false;
}
/** 获取类目 */
const getOptions = async () => {
    try {
        const res = await getCategoryList();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
};
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
            if (element.children.length === 0) {
                delete element.children;
            }
        }
        return {
            text: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
getOptions();

/** 供应商名称关闭 */
const onConfirmSupplierName = (options: any) => {
    showSupplierName.value = false;
    if (options) {
        homePageQueryParams.value.supplierName = options.supplierName
        homePageQueryParams.value.supplierId = options.id;
    }
};
const loadingback = ref(false)
import { onBeforeRouteLeave } from 'vue-router'
// 页面离开路由
onBeforeRouteLeave((_to, from, next) => {
    if (from.meta.title == "添加商品" && loadingback.value == false) {
        // 显示确认对话框
        const confirm = window.confirm('是否退出当前编辑页面，已保存的商品信息将被清空');
        if (confirm) {
            next();
        } else {
            next(false);
        }
    } else {
        next();
    }
});
/** 回退 */
const handleLeft = () => {
    // 商品列表新增返回商品列表
    if (fromRoute.value == 'productList') {
        router.back()
    } else {
        router.push('/research/researchPage')
    }
}

/** 贸易方式 */
const getTradeMode = async () => {
    const res = await getDicts("hm_trade_type");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    tradeModeColumns.value = res.data;
};
getTradeMode();
/** 合作方式 */
const getcooperationMode = async () => {
    const res = await getDicts("hm_cooperation_mode");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    cooperationModeColumns.value = res.data;
};
getcooperationMode();
/** 能否破价 */
const getDiscountPrice = async () => {
    const res = await getDicts("hm_discount");
    res.data.forEach((element) => {
        element.text = element.dictLabel;
        element.value = element.dictValue;
    });
    discountPriceColumns.value = res.data;
};
getDiscountPrice();

/** 类目修改 */
const cascaderShade = ref(false)
const cascaderTimeout = ref()

/** 类目最后选择 */
const onFinish = (value) => {
    show.value = false;
    homePageQueryParams.value.productCategoryName = value.selectedOptions
        .map((option) => option.text)
        .join(",");
    homePageQueryParams.value.categoryId = value.selectedOptions
        .map((option) => option.value)
        .join(",");
};
/** 离开页面、提交移除本地存储 */
const removeLocal = () => {
    // 删除app切换导致得缓存数据问题 清除
    localStorage.removeItem('homePageQueryParams')
    productImageList.value && localStorage.removeItem('productImageList')
    abImageList.value && localStorage.removeItem('abImageList')
    productVideoList.value && localStorage.removeItem('productVideoList')
    voucherImageList.value && localStorage.removeItem('voucherImageList')
    otherImageList.value && localStorage.removeItem('otherImageList')
    customsDeclarationImageList.value && localStorage.removeItem('customsDeclarationImageList')
    customsInformationImageList.value && localStorage.removeItem('customsInformationImageList')
    customsInspectionImageList.value && localStorage.removeItem('customsInspectionImageList')
    customsTestReportImgaeList.value && localStorage.removeItem('customsTestReportImgaeList')
    homePageQueryParams.value = {
        supplierName: "",
        styleName: "",
        category: "",
        productCategoryName: "",
        categoryId: "",
        styleCode: "",
        sellingPoints: "",
        tradeMode: "",
        cooperationMode: "",
        price: "",
        costPrice: "",
        liveStreamingMechanism: "",
        commission: "",
        brokerage: "",
        discountPrice: "",
        supplierId: "",
        productImage: "",
        voucherImage: "",
        otherImage: "",
        customsDeclarationImage: "",
        customsInformationImage: "",
        customsInspectionImage: "",
        customsTestReportImgae: "",
        specs: "",
        // ingredient: "",
        warehouse: "",
        groupName: "",
        brandName: "",

        cooperationMode2: "",
        price2: "",
        costPrice2: "",
        liveStreamingMechanism2: "",
        commission2: "",
        brokerage2: "",

        cooperationMode3: "",
        price3: "",
        costPrice3: "",
        liveStreamingMechanism3: "",
        commission3: "",
        brokerage3: "",
        deliveryTime: "",
        placeDelivery: "",
        placeDeliveryId: "",
        logistics: "",
        eligibility: "",
        factoryStockNum: "",
        noSendArea: "",
        tax: '',
        historyPrice: "",

        bigDate: "",
        isPackageRemind: "",
        packageDeadline: "",
        noAbImage: "",
        bigVideo: "",
    }
    productImageList.value = []
    abImageList.value = []
    productVideoList.value = []
    voucherImageList.value = []
    otherImageList.value = []
    customsDeclarationImageList.value = []
    customsInformationImageList.value = []
    customsInspectionImageList.value = []
    customsTestReportImgaeList.value = []
}
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
const onSubmit = async () => {
    loading.value = true
    const list = JSON.parse(JSON.stringify(homePageQueryParams.value));
    list.noAbImage = getPicByfullPath(abImageList.value)
    list.bigVideo = getPicByfullPath(productVideoList.value)
    list.productImage = getPicByfullPath(productImageList.value)
    list.voucherImage = getPicByfullPath(voucherImageList.value)
    list.otherImage = getPicByfullPath(otherImageList.value)
    list.customsDeclarationImage = getPicByfullPath(customsDeclarationImageList.value)
    list.customsInformationImage = getPicByfullPath(customsInformationImageList.value)
    list.customsInspectionImage = getPicByfullPath(customsInspectionImageList.value)
    list.customsTestReportImgae = getPicByfullPath(customsTestReportImgaeList.value)
    list.isPackageRemind = list.isPackageRemind ? 1 : 0
    if (list.cooperationMode == "供货") {
        delete list.price;
        delete list.commission
        delete list.brokerage
    }
    if (list.cooperationMode2 == "供货") {
        delete list.price2;
        delete list.commission2
        delete list.brokerage2
    }
    if (list.cooperationMode3 == "供货") {
        delete list.price3;
        delete list.commission3
        delete list.brokerage3
    }
    list.hmMechanismsList = [
        { cooperationMode: list.cooperationMode, commission: list.commission, price: list.price, costPrice: list.costPrice, brokerage: list.brokerage, liveStreamingMechanism: list.liveStreamingMechanism },
        { cooperationMode: list.cooperationMode2, commission: list.commission2, price: list.price2, costPrice: list.costPrice2, brokerage: list.brokerage2, liveStreamingMechanism: list.liveStreamingMechanism2 },
        { cooperationMode: list.cooperationMode3, commission: list.commission3, price: list.price3, costPrice: list.costPrice3, brokerage: list.brokerage3, liveStreamingMechanism: list.liveStreamingMechanism3 },

    ]
    // 贸易方式
    list.tradeMode = tradeModeChecked.value
    // 能否破价
    list.discountPrice = discountPriceChecked.value
    // 走仓
    list.warehouse = warehouseChecked.value
    try {
        await addProduct(list);
        loading.value = false
        loadingback.value = true;
        showSuccessToast({ type: "success", message: "新增商品成功" });
        removeLocal();
        router.back();
    } catch (error) {
        loading.value = false
        if (error == 'timeout') {
            showFailToast('新增商品失败');
        }
    }
};

/** 删除 */
const deleteImg = (list: any, index: number) => {
    // 清除AB货得验证
    if (list == abImageList.value) {
        homePageQueryParams.value.noAbImage = ''
    }
    list.splice(index, 1);
};
/** app端隐藏触发保存表单 */
(window as any).saveState = function (arg) {
    if (arg.action == 'save') {
        localStorage.setItem("homePageQueryParams", JSON.stringify(homePageQueryParams.value));
        localStorage.setItem("mechanismArr", JSON.stringify(mechanismArr.value));
        if (productImageList.value.length > 0) {
            localStorage.setItem("productImageList", JSON.stringify(productImageList.value));
        }
        if (abImageList.value.length > 0) {
            localStorage.setItem("abImageList", JSON.stringify(abImageList.value));
        }
        if (productVideoList.value.length > 0) {
            localStorage.setItem("productVideoList", JSON.stringify(productVideoList.value));
        }
        if (voucherImageList.value.length > 0) {
            localStorage.setItem("voucherImageList", JSON.stringify(voucherImageList.value));
        }
        if (otherImageList.value.length > 0) {
            localStorage.setItem("otherImageList", JSON.stringify(otherImageList.value));
        }
        if (customsDeclarationImageList.value.length > 0) {
            localStorage.setItem("customsDeclarationImageList", JSON.stringify(customsDeclarationImageList.value));
        }
        if (customsInformationImageList.value.length > 0) {
            localStorage.setItem("customsInformationImageList", JSON.stringify(customsInformationImageList.value));
        }
        if (customsInspectionImageList.value.length > 0) {
            localStorage.setItem("customsInspectionImageList", JSON.stringify(customsInspectionImageList.value));
        }
        if (customsTestReportImgaeList.value.length > 0) {
            localStorage.setItem("customsTestReportImgaeList", JSON.stringify(customsTestReportImgaeList.value));
        }
    }
}
onUnmounted(() => {
    removeLocal();
    clearTimeout(cascaderTimeout.value)
})
/** app端重新打开后数据保存重新渲染 */
const rendering = () => {
    if (localStorage.getItem('homePageQueryParams')) {
        homePageQueryParams.value = JSON.parse(localStorage.getItem('homePageQueryParams') as string)
    }
    if (localStorage.getItem('mechanismArr')) {
        mechanismArr.value = JSON.parse(localStorage.getItem('mechanismArr') as string)
    }
    if (localStorage.getItem('productImageList')) {
        productImageList.value = JSON.parse(localStorage.getItem('productImageList') as string)
    }
    if (localStorage.getItem('abImageList')) {
        abImageList.value = JSON.parse(localStorage.getItem('abImageList') as string)
    }
    if (localStorage.getItem('productVideoList')) {
        productVideoList.value = JSON.parse(localStorage.getItem('productVideoList') as string)
    }
    if (localStorage.getItem('voucherImageList')) {
        voucherImageList.value = JSON.parse(localStorage.getItem('voucherImageList') as string)
    }
    if (localStorage.getItem('otherImageList')) {
        otherImageList.value = JSON.parse(localStorage.getItem('otherImageList') as string)
    }
    if (localStorage.getItem('customsDeclarationImageList')) {
        customsDeclarationImageList.value = JSON.parse(localStorage.getItem('customsDeclarationImageList') as string)
    }
    if (localStorage.getItem('customsInformationImageList')) {
        customsInformationImageList.value = JSON.parse(localStorage.getItem('customsInformationImageList') as string)
    }
    if (localStorage.getItem('customsInspectionImageList')) {
        customsInspectionImageList.value = JSON.parse(localStorage.getItem('customsInspectionImageList') as string)
    }
    if (localStorage.getItem('customsTestReportImgaeList')) {
        customsTestReportImgaeList.value = JSON.parse(localStorage.getItem('customsTestReportImgaeList') as string)
    }

}
rendering()
/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        productImage: productImageList.value,
        voucherImage: voucherImageList.value,
        otherImage: otherImageList.value,
        customsDeclarationImage: customsDeclarationImageList.value,
        customsInformationImage: customsInformationImageList.value,
        customsInspectionImage: customsInspectionImageList.value,
        customsTestReportImgae: customsTestReportImgaeList.value,
        noAbImage: abImageList.value,
        bigVideo: productVideoList.value
    };

    const maxCounts = {
        productImage: 5,
        voucherImage: 5,
        otherImage: 10,
        customsDeclarationImage: 5,
        customsInformationImage: 5,
        customsInspectionImage: 5,
        customsTestReportImgae: 5,
        noAbImage: 1,
        bigVideo: 1
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);

    if (arg.name == 'noAbImage' && arg.url) {
        homePageQueryParams.value.noAbImage = '有'
    }
};
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};
const postVideo = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "video",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};

//走仓相关
const warehouseChecked = ref()

const discountWarehouse = ref([
    {
        value: 1,
        text: '是',
    },
    {
        value: 0,
        text: '否',
    },

]);


const hm_warehouse_show = computed(() => {

    if (homePageQueryParams.value.productCategoryName?.indexOf('饰品') >= 0) {
        return true
    }
    return false
});


</script>
<style lang="less" scoped>
.dragge_box {
    display: contents;
    // align-items: center;
    // flex-wrap: wrap;
}

.cascaderShade {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 9999;
}

:deep(.van-cell:after) {
    display: none;
}

:deep(.van-nav-bar__left .van-icon) {
    color: #1a1b1c !important;
}

:deep(.van-field__label) {
    width: 100px !important;
}

.add_product {
    background-color: #f6faff;
    width: 100%;
    height: calc(100vh - 90px);
    //   height: 100vh;
    box-sizing: border-box;
    padding: 10px 15px 10px 15px;
    overflow-y: scroll;
}

.add_supplier-background {
    height: 100vh;
    min-height: 850px;
    background-color: #fff;

    .mechanism_title {
        // width: 100%;
        font-weight: 600;
        font-size: 14px;
        color: #1A1B1C;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px 15px 10px 15px;

        .delete_mechanism {
            width: 128px;
            height: 34px;
            border-radius: 22px;
            border: 1px solid #FC2540;
            display: flex;
            justify-content: center;
            align-items: center;
            font-weight: 400;
            font-size: 14px;
            color: #FC2540;

            .van-image {
                width: 14px;
                height: 14px;
            }
        }
    }

    .add_mechanism {
        width: 128px;
        height: 34px;
        border-radius: 22px;
        border: 1px solid #0094FF;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #0094FF;
        margin: auto;

        .van-image {
            width: 14px;
            height: 14px;
        }
    }
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

.label {
    width: 90px;
    margin-right: 12px;
}

.value {
    width: 100%;
    display: flex;
    flex-wrap: wrap;

    video {
        width: 77px;
        height: 77px;
    }

    .imgList {
        position: relative;

        .loading_pic {
            width: 90px;
            height: 90px;
            display: flex;
            align-items: center;
            justify-content: center;
        }


        :deep(.van-image__img) {
            margin-right: 5px;
        }

        :deep(.van-icon) {
            position: absolute;
            top: 0;
            z-index: 100;
            right: 5px;
            font-size: 10px;
            height: 15px;
            width: 15px;
            background-color: #000;
            border-bottom-left-radius: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .delete_icon {
            right: 0px !important;
        }

        :deep(.van-icon-cross:before) {
            margin: 0 0 1px 2px;
        }
    }

    :deep(.van-image__img) {
        width: 90px;
        height: 90px;
    }
}

:deep(.van-form) {
    // padding-bottom: 35px !important;
    background-color: #fff;
}

:deep(.van-popup--bottom) {
    border-radius: 20px 20px 0px 0px !important;
}

:deep(.van-picker-column__item--selected>.van-ellipsis) {
    color: #0094ff;
}

.image-title {
    font-weight: 400;
    font-size: 14px;
    color: #1a1b1c;
    background-color: #fff;
    padding-left: 15px;
    display: flex;
    align-items: center;

    .require_icon {
        color: #ee0a24;
        margin-right: 2px;
    }
}

// van-badge__wrapper van-icon van-icon-arrow van-cell__right-icon</style>
